# -*- coding: utf-8 -*-
import json
from flask import request, jsonify, Flask, g
import opentracing
from ..config import Config

def is_trace_banned(headers):
    '''
        检查请求头部是否有禁止追踪的标志
        请求头部会把no_trace修改改成No-Trace参数名称
        其值为0和1,均为字符串类型,需要转换成整数0和1,其中1表示禁止追踪,0表示启用追踪
    '''
    is_no_trace = headers.get('no_trace','0')
    return int(is_no_trace)

def create_span():
    #默认使用不具有任何操作的noop span
    g.span = Config.noop_tracer.noop_span
    #是否禁止span
    if is_trace_banned(request.headers):
        return
    path = request.path
    context = opentracing.global_tracer().extract(opentracing.Format.HTTP_HEADERS,request.headers)
    if context is not None:
        g.span = opentracing.global_tracer().start_span(path, opentracing.child_of(context))
    else:
        g.span = opentracing.global_tracer().start_span(path)
    g.span.set_tag('path',request.path).set_tag('method',request.method).set_tag('remote_addr',request.remote_addr)
    g.span.set_tag('url',request.url).set_tag('protocol',request.scheme)

def finish_span(response):
    #是否禁止span
    if is_trace_banned(request.headers):
        return response
    g.span.set_tag('status_code',response.status_code)
    #为每个请求注入span id
    data = response.get_json()
    if data is not None:
        data['span_id'] = g.span.span_id
    error = False
    if response.status_code == 500:
        error = True
    g.span.finish(error=error)
    response.set_data(json.dumps(data))
    return response
    
def init_interceptor(app):
    app.before_request(create_span)
    app.after_request(finish_span)
    